// @See: https://pinia.vuejs.org/zh/core-concepts/

import { defineStore } from 'pinia'
import { StorageEnum } from '@/common/enums'
import { getLocalStorage } from '@/utils'
import type { UserState } from './interface'

// 查看浏览器缓存是否有数据
const initialState: UserState = {
  exist: false,
  // @ts-ignore
  userInfo: getLocalStorage(StorageEnum.USER_INFO),
}

export const useUserStore = defineStore('userStore', {
  state(): UserState {
    return {
      ...initialState,
    }
  },

  getters: {
    // 统一使用此属性来判断用户是否登陆
    existGetter: (_state) => {
      return !!localStorage.getItem(StorageEnum.USER_ID)
    },
  },

  actions: {
    /**
     * 更新用户详情信息
     */
    updateUserInfo(userInfo: UserState['userInfo']) {
      this.userInfo = userInfo
      // 缓存用户详情信息
      localStorage.setItem(StorageEnum.USER_INFO, JSON.stringify(userInfo))
      // 缓存用户id
      localStorage.setItem(StorageEnum.USER_ID, `${userInfo?.id}`)
    },

    /**
     * 重置该仓库，会清除缓存数据
     */
    resetStore() {
      this.$state = {
        exist: false,
        userInfo: null,
      }
      window.localStorage.removeItem(StorageEnum.USER_INFO)
      window.localStorage.removeItem(StorageEnum.USER_ID)
    },
  },
})
